package cn.kgc.filter;

import cn.kgc.common.vo.Result;
import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginFilter extends ZuulFilter {
    //过滤的时机
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //优先级，数字越小优先级越高
    @Override
    public int filterOrder() {
        return 0;
    }

    //是否要执行过滤器
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取请求的token
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");

        // 判断token是否有效
        if(token == null){
            // 未登录，返回json结果
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            HttpServletResponse response = ctx.getResponse();
            response.setContentType("application/json;charset=utf-8");
            Result<Object> result = Result.fail(20001, "无效认证，请重新登录");
            try {
                response.getWriter().write(JSON.toJSONString(result));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
        // 有效，则放行
        return null;
    }
}
